package mybatis;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

public class MyBatisDemo {

    private static final Logger log = LoggerFactory.getLogger(MyBatisDemo.class);

    private static SqlSessionFactory sqlSessionFactory = null;

    static {
        try {
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {

        log.info("开始执行！！！！！！！！！！！！！！！！！！！");
        selectListByIds();
    }

    private static void selectList(User user){
        try (SqlSession session = openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            List<User> list = mapper.selectList(user);
            for (int i = 0; i < list.size(); i++) {
                log.info("查询结果： {}", list.get(i));
            }
        }
    }

    private static void selectUser(User user){
        try (SqlSession session = openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            List<User> list = mapper.selectUser(user);
            for (User u : list) {
                log.info("查询结果： {}", u);
            }
        }
    }

    private static void update(User user){
        try (SqlSession session = openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            int updateNum = mapper.update(user);
            log.info("更新数量： {}", updateNum);
        }
    }

    private static void insert(User user){
        try (SqlSession session = openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            int num = mapper.insert(user);
            log.info("新增数量： {}", num);
        }
    }

    private static void selectListByIds(){
        List<Integer> ids = Arrays.asList(1,2);
        try (SqlSession session = openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            List<User> list = mapper.selectListByIds(ids);
            for (User u : list) {
                log.info("查询结果： {}", u);
            }
        }
    }





    private static SqlSession openSession(){
        //事务自动提交
        return sqlSessionFactory.openSession(true);
    }
}
